package com.ouc.ouc.interceptor;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.ouc.pampas.SessionSecurityConstants;
/**
 * 用户登陆拦截器
 */
public class LoginContextInterceptor extends HandlerInterceptorAdapter {

	//不被拦截器拦截的url
	private List<String> noLoginAuthUrlList = new ArrayList<String>();
	public List<String> getNoLoginAuthUrlList() {
		return noLoginAuthUrlList;
	}
	public void setNoLoginAuthUrlList(List<String> noLoginAuthUrlList) {
		this.noLoginAuthUrlList = noLoginAuthUrlList;
	}

	/**
	 * 预处理
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		
		if(!isLogin(request)){
			response.sendRedirect("/login"); 
			return false;
		}
	
		return super.preHandle(request, response, handler);
	}

	/**
	 * 拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 返回方法拦截
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 判断是否登录
	 */
	protected boolean isLogin(HttpServletRequest httpServletRequest) {		
		String currentUrl = httpServletRequest.getRequestURI();
		for(String url : noLoginAuthUrlList){
			if(currentUrl.startsWith(url)){
				return true;
			}
		}
		HttpSession httpSession = httpServletRequest.getSession();
		String userName = (String) httpSession.getAttribute(SessionSecurityConstants.KEY_USER_NAME);
		if (userName == null) {
			return false;
		}
		return true;
	}

}
